﻿using UnityEngine;

namespace Room
{
    class MonsterAIStateRest : MonsterAIStateBase
    {

        private float lastTime;

        protected override void OnEnter()
        {
            lastTime = controller.restTime;
            controller.owner.PlayAnim("standfight");
        }

        protected override void OnLeave()
        {
            
        }

        protected override void OnTick()
        {
            lastTime -= Time.deltaTime;
            if(lastTime<=0&&!controller.owner.IsMoving())
            {
                Vector3 targetPosition;
                if(RandomTarget(out targetPosition))
                {
                    controller.owner.StopTo(targetPosition);
                    controller.SwitchState(MonsterAIState.Move);
                }
            }
            if(controller.PlayerInVisualField())
            {
                controller.SwitchState(MonsterAIState.Pursue);
            }
        }

        bool RandomTarget(out Vector3 targetPosition)
        {
            var center = controller.bornPosition;
            var radius = controller.wanderRadius;

            for (int i = 0; i < 1000; i++)
            {
                Vector3 randomPoint = center + Random.insideUnitSphere * radius;
                NavMeshHit hit;
                if (NavMesh.SamplePosition(randomPoint, out hit, 1.0f, NavMesh.AllAreas))
                {
                    targetPosition = hit.position;
                    return true;
                }
            }
            targetPosition = Vector3.zero;
            return false;
        }
    }
}

